package cn.sun.product.service.impl;

import cn.sun.basic.query.BaseQuery;
import cn.sun.basic.service.impl.BaseServiceImpl;
import cn.sun.basic.util.PageBean;
import cn.sun.product.domain.Product;
import cn.sun.product.domain.ProductDetail;
import cn.sun.product.mapper.ProductDetailMapper;
import cn.sun.product.mapper.ProductMapper;
import cn.sun.product.query.ProductQuery;
import cn.sun.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl extends BaseServiceImpl<Product, ProductQuery> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Transactional
    @Override
    public void delete(Long id) {
        //除了删除自己还要删除详情
        productMapper.delete(id);
        //通过ProductId删除ProductDetail
        productDetailMapper.deleteByProductId(id);
    }

    @Override
    public void save(Product product) {
        productMapper.save(product);
        ProductDetail detail = product.getDetail();
        if (detail!=null){
            detail.setProduct_id(product.getId());
            productDetailMapper.save(detail);
        }
    }

    @Transactional
    @Override
    public void update(Product product) {
        productMapper.update(product);
        //是否有详情
        ProductDetail detail = product.getDetail();
        if (detail!=null){
            if (detail.getId()!=null){
                //有详情
                productDetailMapper.update(detail);
            }else{
                productDetailMapper.save(detail);
            }
        }
    }


    @Override
    public ProductDetail getDetailByProductId(Long productId) {
        return productDetailMapper.findByProductId(productId);
    }

    @Transactional
    @Override
    public void bulkdel(List<Long> ids) {
        productDetailMapper.bulkdel(ids);
        productMapper.bulkdel(ids);
    }

    @Override
    public void onOroff(List<Long> ids, int state) {
        Map<String,Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("state", state);
        map.put("time", new Date());
        if (state==0){
            productMapper.offsaleupdates(map);
        }else {
            productMapper.onsaleupdates(map);
        }
    }

    @Override
    public PageBean<Product> prefindPage(ProductQuery query) {
        Integer total = productMapper.findNum(query);
        if (total==null){
            return new PageBean<>();
        }
        List<Product> products = productMapper.findPage(query);
        return new PageBean<Product>(total,products);
    }

    @Override
    public Product prefindOne(Long id) {
        return productMapper.prefindOne(id);
    }


}
